package com.lkb.administrator.okuweather;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lkb.administrator.okuweather.db.City;
import com.lkb.administrator.okuweather.db.County;
import com.lkb.administrator.okuweather.db.Province;
import com.lkb.administrator.okuweather.util.HttpUtil;
import com.lkb.administrator.okuweather.util.UtilIty;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static android.content.ContentValues.TAG;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ChooseAreaFrament.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ChooseAreaFrament#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ChooseAreaFrament extends Fragment {

    public  static   final  int LEVEL_PROVICE = 0;
    public  static   final  int LEVEL_City = 1;
    public  static   final  int LEVEL_County = 2;

    private ProgressDialog  progressDialog;
    private TextView titleText;
    private Button  backButton;
    private ListView listView;
    private ArrayAdapter<String> adapter;

    private List<String> dataList = new ArrayList<>();

    //
    private  List<Province>  provinceList;
    private  List<City>  cityList;
    private  List<County>  countryList;


    private Province selectPro;
    private City selectCity;
    private  int currentLevel;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.choose_area,container,false);
        titleText = (TextView) view.findViewById(R.id.title_text);
        backButton = (Button) view.findViewById(R.id.back_button);
        listView = (ListView) view.findViewById(R.id.list_view);
        adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1,dataList);
        listView.setAdapter(adapter);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (currentLevel == LEVEL_PROVICE){


                    selectPro = provinceList.get(position);
                    queryCity();
                }else  if (currentLevel == LEVEL_City){

                    selectCity = cityList.get(position);
                    queryCountry();

                }else  if (currentLevel == LEVEL_County){

                    String weatherid = countryList.get(position).getWeatherId();

                    if (getActivity() instanceof MainActivity){

                        Intent intent = new Intent(getActivity(),WeatherActivity.class);
                        intent.putExtra("weather_id",weatherid);
                        startActivity(intent);
                        getActivity().finish();

                    }else if (getActivity() instanceof WeatherActivity) {

                        WeatherActivity weatherActivity = (WeatherActivity)getActivity();
                        weatherActivity.drawerLayout.closeDrawers();
                        weatherActivity.swirefresh.setRefreshing(true);
                        weatherActivity.requerst(weatherid);


                    }







                }









            }
        });

        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentLevel == LEVEL_County){


                    queryCity();
                }else  if (currentLevel == LEVEL_City){

                    queryPro();
                }


            }
        });

        queryPro();











    }

    private  void queryPro(){
        titleText.setText("中国");
        backButton.setVisibility(View.GONE);
        provinceList = DataSupport.findAll(Province.class);
        if (provinceList.size() > 0 ){

            dataList.clear();

            for (Province temp  : provinceList){

                dataList.add(temp.getProviceName());

            }

            adapter.notifyDataSetChanged();

            listView.setSelection(0);

            currentLevel = LEVEL_PROVICE;



        }else  {
            String address = "http://guolin.tech/api/china";
            queryFormServce(address,"province");



        }




    }

    private  void queryCity(){
        titleText.setText(selectPro.getProviceName());
        backButton.setVisibility(View.VISIBLE);
        cityList = DataSupport.where("provinceid = ? ",String.valueOf(selectPro.getId())).find(City.class);

        if (cityList.size() > 0){
            dataList.clear();

            for (City city : cityList){

                dataList.add(city.getCityName());


            }

            adapter.notifyDataSetChanged();

            listView.setSelection(0);

            currentLevel = LEVEL_City;




        }else  {

            int proCode = selectPro.getProviceCode();

            String address = "http://guolin.tech/api/china/" + proCode;

            queryFormServce(address,"city");


        }








    }

    private  void queryCountry() {

        titleText.setText(selectCity.getCityName());

        backButton.setVisibility(View.VISIBLE);

        countryList = DataSupport.where("cityid = ?",String.valueOf(selectCity.getId())).find(County.class);


        if (countryList.size() > 0){

            dataList.clear();

            for (County contry : countryList){

                dataList.add(contry.getCountyName());




            }

            adapter.notifyDataSetChanged();

            listView.setSelection(0);

            currentLevel = LEVEL_County;





        }else {

            int proCode = selectPro.getProviceCode();
            int cityCode = selectCity.getCityCode();

            String address = "http://guolin.tech/api/china/" + proCode + "/" + cityCode;

            queryFormServce(address,"country");






        }






    }

    private  void queryFormServce(String address,final String type){

        showProgressDialog();

        HttpUtil.SendOkHttpRequest(address, new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        closeProgressDialog();

                        Toast.makeText(getContext(),"加载失败",Toast.LENGTH_SHORT).show();


                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String responseText = response.body().string();

                Log.d(TAG, responseText);

                boolean result = false;
                if ("province".equals(type)){

                    result = UtilIty.handleProviceResponce(responseText);

                }else if ("city".equals(type)){

                    result = UtilIty.handleCityResponce(responseText,selectPro.getId());

                }else  if ("country".equals(type)){

                    result = UtilIty.handleCountryResponce(responseText,selectCity.getId());

                }

                if (result){

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            closeProgressDialog();

                            if ("province".equals(type)){

                               queryPro();

                            }else if ("city".equals(type)){

                                queryCity();

                            }else  if ("country".equals(type)){

                                queryCountry();

                            }








                        }
                    });





                }










            }
        });









    }

    public void showProgressDialog(){

        if (progressDialog == null){

            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setTitle("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);


        }

        progressDialog.show();



    }

    private void closeProgressDialog(){

        if (progressDialog != null){


            progressDialog.dismiss();
        }



    }

}




